package com.demo.function.office.word;

import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuweiye
 * @since 2021/4/7
 */
@Slf4j
public class PdfUtil {

    /**
     * dpi越大转换后越清晰，相对转换速度越慢
     */
    private static final Integer DPI = 100;

    /**
     * 转换后的图片类型
     */
    private static final String IMG_TYPE = "png";

    /**
     * PDF转图片
     *
     * @param filePath PDF文件的二进制流
     * @return 图片文件的二进制流
     */
    public static List<byte[]> pdfToImage(String filePath, String outPath) throws IOException {
        List<byte[]> result = new ArrayList<>();
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < document.getNumberOfPages(); ++i) {
                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
                ImageIO.write(bufferedImage, IMG_TYPE, new File(outPath));
            }
        }
        return result;
    }

    /**
     * 替换目标文字，生成新的pdf文件
     *
     * @param src  目标pdf路径
     * @param dest 新pdf的路径
     * @throws Exception
     */

    public static void manipulatePdf(String src, String dest) throws Exception {
        PdfReader reader = new PdfReader(src);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        int numberOfPages = reader.getNumberOfPages();
        for (int i = 1; i <= numberOfPages; i++) {
            PdfContentByte canvas = stamper.getOverContent(i);
            canvas.beginText();
            //设置字体和大小
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Font font = new Font(bf, 20, Font.BOLD);
            canvas.setFontAndSize(font.getBaseFont(), 20);
            //设置字体的输出位置
            canvas.setTextMatrix(55f, 500f);
            //要输出的text
            canvas.showText("生成的文本");
            canvas.endText();
        }
        stamper.close();
        reader.close();

    }

}
